#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Export Item Detabase Toolkit

Mikan Python Web Framework
"""

__author__ = "K.Sonohara"
__status__ = "develop"
__version__ = "0.0.0_36"
__date__    = "2014/01/05"
__license__ = 'LGPL'

# ------------------------------------------------------------
## Import Section
# ------------------------------------------------------------
# Python
if __name__ == '__main__':
	import sys
	sys.path.append(".")
	sys.path.append("src")
import json

# ESiPC

# Mikan
from mikan.idt import AbstractMikanItemDBToolkit
from mikan.core import MIKAN
from mikan.item.attribute import to_value

# ------------------------------------------------------------
## Variable Section
# ------------------------------------------------------------

# ------------------------------------------------------------
## Function Section
# ------------------------------------------------------------

# ------------------------------------------------------------
## Class Section
# ------------------------------------------------------------
class MIKAN_IDT_IMPORT(MIKAN):
	TYPE_JSON = "json"

class AbstractMikanImportIDT(AbstractMikanItemDBToolkit, MIKAN_IDT_IMPORT):
	def __init__(self, itemdb):
		super(AbstractMikanImportIDT, self).__init__(itemdb)

class MikanImportIDT(AbstractMikanImportIDT):
	def __init__(self, itemdb):
		super(MikanImportIDT, self).__init__(itemdb)

	def imports(self, atype, data, newid=True, update=True, dohash=True):
		return self.import_entities(atype, data, newid, update, dohash)

	def import_entities(self, atype, data, newid=True, update=True, dohash=True):
		if not data:
			return None

		if atype == MIKAN_IDT_IMPORT.TYPE_JSON:
			return self.import_json_entities(data, newid, update, dohash)
		return None

	def import_json_entities(self, data, newid=True, update=True, dohash=True):
		#

		result = []
		items = json.loads(data, 'UTF-8')["item"]
		if items:
			for id, item in items.items():
				r = self.import_json_entitiy(id, item, newid, update, dohash)
				if r:
					result.append(r)
		return result

	def _loader(self, name):
		try:
			mod = __import__(name)
		except:
			mod_list = name.split('.')
			mod = __import__('.'.join(mod_list[:-1]))

		components = name.split('.')
		for comp in components[1:]:
			mod = getattr(mod, comp)
		return mod

	def import_json_entitiy(self, id, data, newid=True, update=True, dohash=True):
		c = self._loader(data["class"])

		e = None
		u = False
		if (not newid):
			try:
				e = self.itemdb.get(c, id)
				if e:
					u = update
			except:
				pass
		if e == None:
			e = c()
		for k,v in data.items():
			if e.attributes.has_key(k):
				a = to_value(self.itemdb, e.attributes[k], v, dohash)
				setattr(e, k, a)

		if u:
			return self.itemdb.update(e)
		else:
			if not newid:
				e.id = id
			return self.itemdb.create(e, newid=newid)

		return None

# ------------------------------------------------------------
## Main Section
# ------------------------------------------------------------
if __name__ == '__main__':
	pass

# ------------------------------------------------------------
